<template>
  <div class="sbody">
    <headMain />
    <div class="userbox">
      <div class="userleft">
        <div class="usertop">
          <div class="usert">
            <div>个人资料</div>
            <!-- <div class="xgzl">修改资料</div> -->
          </div>
          <div class="userboxs">
            <div class="userimg"></div>
            <div class="username"
              >用户姓名：<span>{{ userdata.studentName }}</span></div
            >
            <div class="username"
              >所属班级：<span>{{ userdata.organizationName }}</span></div
            >
            <div class="upuser" @click="uploadShow = true">修改组织</div>
          </div>
        </div>
        <div class="userbottom">
          <div class="usert">
            <div>训练统计</div>
          </div>
          <div ref="charts" class="chart-container"> </div>
        </div>
      </div>
      <div class="userright">
        <div class="tpinputbox">
          <a-input
            class="tpinputzds"
            v-model="formModel.examineName"
            placeholder="请输入图谱名称"
            allow-clear
          />
          <div class="tpbutton" @click="onPageChange(1)">搜索</div>
          <div class="tpbutton tpbuttonnthchild" @click="reset">重置</div>
        </div>
        <a-table
          ref="userList"
          row-key="userId"
          page-position="bottom"
          :pagination="pagination"
          :columns="columns"
          :data="datas"
          :stripe="true"
          :bordered="{ cell: true }"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        ></a-table>
      </div>
    </div>
    <!-- 修改密码 -->
    <!-- 修改密码弹窗 -->
    <!-- <a-modal
      class="df"
      v-model:visible="uploadShow"
      @cancel="uploadCancel"
      :on-before-ok="uploadCheck"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 修改密码 </template>
      <a-form ref="uploadModel" :rules="uploadRules" :model="uploadForm">
        <a-row style="margin-bottom: 16px">
          <a-form-item field="oldPassword" label="旧密码">
            <a-input-password
              v-model="uploadForm.oldPassword"
              placeholder="请输入旧密码"
              :style="{ width: '320px' }"
              :defaultVisibility="false"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="newPassword" label="新密码">
            <a-input-password
              v-model="uploadForm.newPassword"
              placeholder="请输入新密码"
              :style="{ width: '320px' }"
              :defaultVisibility="false"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="nnewPassword" label="确认密码">
            <a-input-password
              @input="erpassfn"
              v-model="uploadForm.nnewPassword"
              placeholder="请输入新密码"
              :style="{ width: '320px' }"
              :defaultVisibility="false"
              allow-clear
            />
          </a-form-item>
          <div class="lc" v-if="byyshow"> 两次输入密码不一致,请重新输入</div>
        </a-row>
      </a-form>
    </a-modal> -->
    <a-modal
      class="df"
      v-model:visible="uploadShow"
      @cancel="uploadCancel"
      :on-before-ok="uploadChecks"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 修改组织 </template>
      <a-form ref="uploadModel" :rules="uploadRuless" :model="uploadForms">
        <a-row>
          <a-form-item field="organizationId" label="组织">
            <a-tree-select
              :allow-search="true"
              :allow-clear="true"
              :fieldNames="{
                key: 'id',
                title: 'name',
                children: 'children',
              }"
              :data="treeData"
              v-model="uploadForms.organizationId"
              placeholder="请选择组织"
              :style="{ width: '320px' }"
            ></a-tree-select>
          </a-form-item>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive, computed } from 'vue';
  import useLoading from '@/hooks/loading';
  import { Message } from '@arco-design/web-vue';
  import headMain from '@/views/headmain/index.vue';
  import * as echarts from 'echarts';
  import { getUser, getbars, getlist } from '@/api/tplist.ts';
  import { updatePassword, updateOrg, organization } from '@/api/user.ts';
  import useUser from '@/hooks/user';
  const { loading, setLoading } = useLoading(true);
  const usershow = ref(false);
  // 修改密码
  const uploadForm = ref({
    oldPassword: '',
    newPassword: '',
    nnewPassword: '',
  });
  // 修改组织
  const uploadForms = ref({
    organizationId: '',
  });
  const { logout } = useUser();
  const uploadShow = ref(false);
  const uploadCancel = () => {
    uploadForm.value = [];
    byyshow.value = false;
    uploadShow.value = false;
  };
  const treeData = ref([]);
  const organizationfn = () => {
    organization().then((res) => {
      if (res.code == 200) {
        treeData.value = res.data;
        // console.log('查询组织树', res);
      }
    });
  };
  organizationfn();
  const byyshow = ref(false);
  // 二次输入密码校验
  const uploadModel = ref();
  const erpassfn = (value) => {
    uploadModel.value.validateField('nnewPassword', (errorMessage) => {
      if (!errorMessage) {
        console.log('通过校验');
        if (uploadForm.value.nnewPassword != '') {
          if (value != uploadForm.value.newPassword) {
            byyshow.value = true;
          } else {
            byyshow.value = false;
          }
        }
      }
    });
  };

  // 修改组织

  const uploadChecks = (done) => {
    // if (loading.value) {
    //   done(false);
    //   return;
    // }

    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);

    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors && !byyshow.value) {
          updateOrg({
            studentId: studentId.value,
            organizationId: uploadForms.value.organizationId,
          }).then((res) => {
            if (res.code == '200') {
              Message.success({
                //   content: res.message,
                content: '修改成功!',
              });
              uploadForms.value = [];
              byyshow.value = false;
              uploadShow.value = false;
              fetchData();
              getBarData();
              done(true);
            } else {
              Message.success({
                //   content: res.message,
                content: res.message,
              });
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const uploadCheck = (done) => {
    // if (loading.value) {
    //   done(false);
    //   return;
    // }

    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    console.log('执行了1', byyshow.value);
    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        console.log('执行了', errors, byyshow.value);
        if (!errors && !byyshow.value) {
          updatePassword(uploadForm.value).then((res) => {
            if (res.code == '200') {
              Message.success({
                //   content: res.message,
                content: '修改成功!',
              });
              uploadForm.value = [];
              byyshow.value = false;
              uploadShow.value = false;
              handleLogout();
              done(true);
            } else {
              Message.success({
                //   content: res.message,
                content: res.message,
              });
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const handleLogout = () => {
    logout();
  };
  const uploadRuless = {
    organizationId: [
      {
        required: true,
        message: '请选择组织',
      },
    ],
  };
  const uploadRules = {
    //  /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!#$%^&*])[\da-zA-Z!#$%^&*]{8,16}$/

    oldPassword: [
      {
        required: true,
        message: '请输入旧密码',
      },
    ],
    newPassword: [
      {
        required: true,
        message: '请输入新密码',
      },
      {
        match: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*?])[^\s]{6,16}$/,
        // /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/,
        message: '6-16位的,需包含大写字母、小写字母、特殊符号及数字',
      },
    ],
    nnewPassword: [
      {
        required: true,
        message: '请输入新密码',
      },
      {
        match: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*?])[^\s]{6,16}$/,
        message: '6-16位的,需包含大写字母、小写字母、特殊符号及数字',
      },
    ],
  };
  // 修改密码结束
  const userdata = ref([]);
  const charts = ref<HTMLElement | null>(null);
  const roomData = reactive({
    xAxis: [],
    yAxis: [],
  });
  const datas = ref([]);
  const initCharts = () => {
    if (charts.value) {
      const myChart = echarts.init(charts.value);
      console.log('xAxis:', roomData.xAxis, 'yAxis:', roomData.yAxis); // 在设置选项前打印数据
      const option: echarts.EChartsOption = {
        // tooltip: {
        //   trigger: 'axis',
        //   formatter: '{a}<br />{b}: {c}次',
        // },
        legend: {
          left: '30',
        },
        xAxis: {
          type: 'category',
          data: roomData.xAxis,
          axisLabel: {
            rotate: 30, // 旋转标签
            interval: 0, // 显示所有标签
          },
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            itemStyle: {
              color: '#0C71FF', // 设置柱子的颜色
            },

            // name: '已预约次数',
            type: 'bar',
            barWidth: '50%',
            barMaxWidth: 21, // 设置柱子的最大宽度
            // label: {
            //   show: true,
            //   position: 'inside',
            //   formatter: '{c}次',
            // },
            data: roomData.yAxis,
          },
        ],
      };
      myChart.setOption(option);
    } else {
      console.error('charts.value 为 null 或 undefined');
    }
  };

  const getBarData = async () => {
    try {
      const userResponse = await getUser();
      if (userResponse.code === 200) {
        // console.log('获取学生信息成功');
        userdata.value = userResponse.data;
        const barsResponse = await getbars({
          studentId: userResponse.data.studentId,
        });
        if (barsResponse.code === 200) {
          console.log('获取到数据', barsResponse.data);
          // Update roomData with fetched data
          roomData.xAxis = barsResponse.data.xAxis;
          roomData.yAxis = barsResponse.data.yAxis;
          initCharts(); // Initialize chart after data is set
        }
      }
    } catch (error) {
      console.error('Error fetching data', error);
    }
  };
  const studentId = ref('');
  const fetchData = () => {
    // 查询学生信息
    getUser().then((res) => {
      if (res.code == 200) {
        console.log('查询学生信息完成', res.data);
        uploadForms.value.organizationId = res.data.organizationId;
        studentId.value = res.data.studentId;
        const data = {
          pageNum: pagination.current,
          ...pagination,
          examineName: '',
          studentId: res.data.studentId,
        };
        getlist(data).then((res) => {
          if (res.code == 200) {
            datas.value = res.data.list;
            pagination.total = res.data.total;
            pagination.current = res.data.pageNum;
            // console.log(
            //   '查询列表成功',
            //   res.data,
            //   pagination.total,
            //   pagination.current
            // );
          }
        });
      }
    });
  };
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '训练名称',
      dataIndex: 'medicineAtlasName',
    },
    {
      title: '训练时间',
      dataIndex: 'startTime',
    },

    {
      title: '学生姓名',
      dataIndex: 'studentName',
    },
    {
      title: '训练次数',
      dataIndex: 'trainNum',
    },
  ]);
  fetchData();
  // 重置
  const reset = () => {
    formModel.value = {};
    fetchData();
  };
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };
  onMounted(() => {
    getBarData();
  });
  const formModel = ref({
    examineName: '',
  });
</script>

<style scoped>
  .tpinputzds {
    background-color: #f5f6fa !important;
  }
  .chart-container {
    width: 100%; /* 或者具体的像素值 */
    height: 400px; /* 也要设置具体的高度 */
  }
  .userbox {
    display: flex;
    width: auto;

    position: absolute;
    top: 130px;
    left: 50%;
    transform: translate(-50%);
  }
  .userleft {
    display: flex;
    flex-direction: column;
  }
  .usertop {
    width: 535px;
    height: 340px;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
    display: flex;
    flex-direction: column;
    padding: 15px;
  }
  .userbottom {
    width: 535px;
    height: 431px;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
    margin: 10px 0;
    display: flex;
    flex-direction: column;
    padding: 15px;
  }
  .sbody {
    background: #f5f6fa !important;
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
  }
  .userright {
    width: 648px;
    height: 780px;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
    margin-left: 10px;
    padding: 15px;
    overflow: hidden;
  }
  .usert {
    border-left: 3px solid #0c71ff;
    height: 18px;
    padding-left: 5px;
    display: flex;
    justify-content: space-between;
  }
  .xgzl {
    width: 82px;
    height: 28px;
    background: #0c71ff;
    border-radius: 4px 4px 4px 4px;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  .userboxs {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .username {
    color: #999999;
    font-size: 18px;
    margin: 10px 0;
    width: 180px;

    text-wrap: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .username span {
    color: #000000;
    font-size: 18px;
  }
  .upuser {
    width: 106px;
    height: 28px;
    background: #0c71ff;
    border-radius: 4px 4px 4px 4px;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    margin: 25px 0;
  }
  .userimg {
    width: 80px;
    height: 80px;
    background: #dcdfe6;
    border-radius: 50%;
    overflow: hidden;
    margin: 35px 0;
  }
  .tpinputbox {
    display: flex;
    margin: 10px 0;
  }

  .tpbutton {
    cursor: pointer;
    width: 120px;
    font-size: 18px;
    height: 35px;
    text-align: center;
    line-height: 35px;
    background: #0c71ff;
    border-radius: 4px 4px 4px 4px;
    color: #ffffff;
    margin: 0 10px;
  }
  .tpbuttonnthchild {
    margin-right: 0px;
  }
</style>
